<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\DrainageLink\Action\Operation;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ChannelCode\Contract\ChannelCodeContract;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkClickContract;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkContract;
use MoChat\Plugin\RoomAutoPull\Contract\WorkRoomAutoPullContract;

/**
 * 引流链接H5- 获取标题.
 *
 * Class ContactData.
 * @Controller
 */
class GetTitle extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var DrainageLinkContract
     */
    protected $drainageLink;

    /**
     * @Inject
     * @var ChannelCodeContract
     */
    protected $channelCode;

    /**
     * @Inject
     * @var WorkRoomAutoPullContract
     */
    protected $workRoomAutoPull;

    /**
     * @Inject
     * @var DrainageLinkClickContract
     */
    protected $drainageLinkClick;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/operation/drainageLink/getTitle", methods="get")
     * @return array 返回数组
     */
    public function handle(): array
    {
        # # 接收参数
        $params = [
            'id' => (int) $this->request->input('id', 1),
        ];
        # # 参数验证
        $this->validated($params);

        # # 查询数据
        $link = $this->drainageLink->getDrainageLinkById($params['id'], ['page_title', 'corp_nickname', 'corp_avatar']);
        if (empty($link)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未找到该链接');
        }

        return [
            'pageTitle' => $link['pageTitle'] ?? '',
            'corpNickname' => $link['corpNickname'] ?? '',
            'corpAvatar' => ! empty($link['corpAvatar']) ? file_full_url($link['corpAvatar']) : '',
        ];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'id' => 'required | integer | min:0 | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'id.required' => '链接ID 必填',
            'id.integer' => '链接ID 必需为整数',
            'id.min' => '链接ID 不可小于1',
        ];
    }
}
